/*
 * @Author       : 吴豪
 * @Date         : 2021-12-4 15:56:22
 * @FilePath     : \book-manage-front\src\pages\User\login\index.tsx
 * @Description  : 登录页面
 */

import React, { useEffect, useState, useRef } from 'react';
import type { ProFormInstance } from '@ant-design/pro-form';
import ProForm, { ProFormText } from '@ant-design/pro-form';
import { history, useModel } from 'umi';
import styles from './index.less';
import { setToken } from '@/utils/utils';
import { LockTwoTone, SafetyCertificateOutlined, UserOutlined } from '@ant-design/icons';
import { getImageCode, getPresentUsername, userLogin } from '@/services/login';
import Setting from '../../../../config/defaultSettings';
import { DefaultFooter } from '@ant-design/pro-layout';
import type { ImageCodeType } from '@/dataType';

/**
 * 此方法会跳转到 redirect 参数所在的位置
 */
const goto = () => {
  if (!history) return;
  setTimeout(() => {
    const { query } = history.location;
    const { redirect } = query as { redirect: string };
    history.replace(redirect || '/');
  }, 10);
};

/**
 * 登录页面，对电话号、密码、验证码的验证，实现登录功能
 * @returns
 */
const Login: React.FC = () => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const [imageInfo, setImageInfo] = useState<ImageCodeType>({
    imageCodeKey: '',
    imageCodeBase64: '',
  });

  //获取登录用户的信息
  const fetchUserInfo = async () => {
    const data = await getPresentUsername();
    if (data) {
      setInitialState({
        ...initialState,
        currentUser: {
          ...data,
          avatar: '',
        },
      });
    }
  };

  /**
   * 获取服务端传来的图形验证码
   */
  const getImageInfo = async () => {
    const data = await getImageCode();
    setImageInfo(data);
  };

  /**
   * 获取列表数据
   */
  const loginRef = useRef<
    ProFormInstance<{
      phone: string;
      password: string;
      imageCode: string;
      imageCodeKey: string;
    }>
  >();

  /**
   * 自动刷新图形验证码
   */
  useEffect(() => {
    getImageInfo();
  }, []);

  return (
    <div className={styles.container}>
      <img className={styles.global} src="/Global.png" alt="Global" />
      <img className={styles.button} src="/button.png" alt="button" />
      <div className={styles.content}>
        <h1 className={styles.h1}>
          <img className={styles.logo} alt="logo" src="../logo.svg" />
          {Setting.title}
        </h1>
        <p className={styles.text}>
          Yunnan easy to use software Co., Ltd., Internet information service.
        </p>
        <div className={styles.main}>
          <div className={styles.loginText}>
            <strong>登录</strong>
          </div>
          <ProForm
            formRef={loginRef}
            submitter={{
              searchConfig: {
                submitText: '登录',
              },
              render: (_, dom) => dom.pop(),
              submitButtonProps: {
                size: 'large',
                style: {
                  width: '100%',
                },
              },
            }}
            /**
             * 采集用户输入的信息，进行身份验证
             */
            onFinish={async (values: any) => {
              const params = {
                phone: values.phone,
                password: values.password,
                imageCode: values.imageCode,
                imageCodeKey: imageInfo?.imageCodeKey || '',
              };
              const data = await userLogin(params);
              if (data) {
                setToken(data.token);
                await fetchUserInfo();
                goto();
              } else {
                loginRef.current?.resetFields(['imageCode']);
                getImageInfo();
              }
            }}
          >
            <>
              <ProFormText
                name="phone"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined className={styles.prefixIcon} />,
                }}
                placeholder="用户账号"
                rules={[
                  {
                    required: true,
                    message: '请输用户账号!',
                  },
                  {
                    len: 11,
                    message: '请输入正确的手机号',
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockTwoTone className={styles.prefixIcon} />,
                }}
                placeholder="用户密码"
                rules={[
                  {
                    required: true,
                    message: '请输入用户密码！',
                  },
                  {
                    pattern: new RegExp(/^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{6,20}$/),
                    message: '请输入6-20位字母+数字的密码，不能有空格！',
                  },
                ]}
              />
              <ProFormText
                name="imageCode"
                fieldProps={{
                  size: 'large',
                  prefix: <SafetyCertificateOutlined className={styles.prefixIcon} />,
                  suffix: (
                    <img
                      src={imageInfo.imageCodeBase64}
                      className={styles.loginImage}
                      onClick={() => getImageInfo()}
                    />
                  ),
                }}
                rules={[
                  {
                    required: true,
                    message: '请输入图片验证码！',
                  },
                ]}
                placeholder="图片验证码"
              />
            </>
          </ProForm>
        </div>
      </div>
      <DefaultFooter
        copyright={'Yunnan easy to use software Co., Ltd., Internet information service.'}
        links={[
          {
            key: 'Easy to use software',
            title: 'Easy to use software',
            href: 'https://baike.baidu.com/item/%E4%BA%91%E5%8D%97%E6%98%93%E7%94%A8%E8%BD%AF%E4%BB%B6%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8/23224589?fr=aladdin',
            blankTarget: true,
          },
          {
            key: 'github',
            title: <img src="../Group.png" />,

            href: 'https://baike.baidu.com/item/%E4%BA%91%E5%8D%97%E6%98%93%E7%94%A8%E8%BD%AF%E4%BB%B6%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8/23224589?fr=aladdin',
            blankTarget: true,
          },
          {
            key: 'UI Design',
            title: 'UI Design',
            href: 'https://baike.baidu.com/item/%E4%BA%91%E5%8D%97%E6%98%93%E7%94%A8%E8%BD%AF%E4%BB%B6%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8/23224589?fr=aladdin',
            blankTarget: true,
          },
        ]}
      />
    </div>
  );
};

export default Login;
